package com.company.project.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.utils.DataResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.company.project.mapper.SysSmscodeMapper;
import com.company.project.entity.SysSmscodeEntity;
import com.company.project.service.SysSmscodeService;

import java.util.Date;
import java.util.Random;


@Service("sysSmscodeService")
public class SysSmscodeServiceImpl extends ServiceImpl<SysSmscodeMapper, SysSmscodeEntity> implements SysSmscodeService {

    @Autowired
    private SysSmscodeMapper sysSmscodeMapper;

    @Override
    public DataResult getSmscode(String phone) {
        Random random = new Random();
        int randomNumber = random.nextInt(9000) + 1000;
        System.out.println("Generated random number: " + randomNumber);

        SysSmscodeEntity sysSmscode = new SysSmscodeEntity();
        sysSmscode.setPhone(phone);
        sysSmscode.setSmscode(String.valueOf(randomNumber));
        sysSmscode.setTime(new Date());
        //先删除在插入
        sysSmscodeMapper.delete(Wrappers.<SysSmscodeEntity>lambdaQuery().eq(SysSmscodeEntity::getPhone,phone));
        int insert = sysSmscodeMapper.insert(sysSmscode);

        if (insert > 0) {
            return DataResult.success(String.valueOf(randomNumber));
        } else {
            return DataResult.fail("验证码发送失败");
        }
    }
}